<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item
            :to="{ name: 'MatchList' }"
            class="breadcrumb_active_item"
            >赛事名称管理</el-breadcrumb-item
          >
          <el-breadcrumb-item>{{ pageTitle }}</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="match_from_content">
        <!-- 表单 -->
        <el-row>
          <el-col :span="22">
            <el-form
              ref="submitFrom"
              :model="submitData"
              label-width="140px"
              :rules="rules"
              :disabled="editKey == 3"
            >
              <el-form-item
                label="赛事名称名称"
                size="small"
                prop="title"
                required
              >
                <el-col :span="8">
                  <el-input
                    v-model="submitData.title"
                    maxlength="20"
                    placeholder="请输入培训名称"
                  ></el-input>
                </el-col>
              </el-form-item>

              <el-form-item label="封面图" size="small" prop="image_path">
                <el-col :span="8">
                  <el-upload
                    class="match_from_uploader"
                    :data="uploadData"
                    :action="actionUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :headers="headers"
                  >
                    <img
                      v-if="imageShowUrl"
                      :src="imageShowUrl"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-col>
              </el-form-item>

              <el-form-item label="赛事名称日期" size="small" prop="event_date">
                <el-col :span="8">
                  <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    v-model="submitData.event_date"
                    style="width: 100%"
                    :format="format"
                    :value-format="valueFormat"
                  ></el-date-picker>
                </el-col>
              </el-form-item>

              <el-form-item label="地址" size="small" prop="place" required>
                <el-col :span="8">
                  <el-input
                    v-model="submitData.place"
                    maxlength="30"
                  ></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="上传制证状态的URL" size="small" prop="url">
                <el-col :span="8">
                  <el-input v-model="submitData.url" maxlength="30"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="详情" size="small" prop="detail">
                <editor v-model="submitData.detail" :init="init" />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-row>
    <div class="match_from_btn_box" v-if="editKey != 3">
      <el-button
        type="danger"
        size="mini"
        v-if="userType == 0"
        @click="saveBtn()"
        >保存</el-button
      >
      <el-button type="info" size="mini" @click="backBtn()">
        返回上一页
      </el-button>
    </div>
    <div class="match_from_btn_box" v-else>
      <el-button type="danger" size="mini" @click="backBtn()">返回</el-button>
    </div>
  </div>
</template>
<style src="../../assets/css/match/matchFrom.css" scoped></style>

<script>
// 引入富文本
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver/theme";
import "tinymce/plugins/image"; // 图片
import "tinymce/plugins/imagetools"; // 图片裁剪
import "tinymce/plugins/media";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/advlist";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/colorpicker";
import "tinymce/skins/ui/oxide/skin.css";
import "tinymce/icons/default";
// import "../../../public/tinymce/plugins/lineheight/plugin"; // 行高
// import "../../../public/tinymce/plugins/indent2em/plugin"; // 首行缩进
// import "../../../public/tinymce/plugins/letterspacing/index"; // 文字间距
// import "../../../public/tinymce/plugins/image/index"; // 图片

export default {
  name: "MatchFrom",
  components: {
    Editor,
  },
  data() {
    return {
      userType: this.$store.state.loginUserType == "ADMINLOGINUSERCH" ? 0 : 1, // 用户类型;1. 普通; 0. 超级;
      baseAPIUrl: this.$store.state.baseAPIUrl, //默认路径
      actionUrl: this.$store.state.baseAPIUrl + "/upload/uploadFile", // 上传路径
      // actionUrl: "/upload/uploadImage", // 上传路径
      imageShowUrl: "", // 预览路径
      uploadData: {
        source: 5,
      }, // 上传额外参数
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 上传用token
      matchId: "", // 培训赛事名称id
      pageTitle: "", // 页面名称
      editKey: 0, // 是否编辑
      submitData: {
        title: "",
        image_path: "",
        event_date: "",
        place: "",
        detail: "",
        url: "",
      }, // 培训数据
      rules: {
        title: [
          { required: true, message: "请输入赛事名称名称", trigger: "blur" },
        ],
        event_date: [
          { required: true, message: "请选择赛事名称日期", trigger: "change" },
        ],
        place: [{ required: true, message: "请输入地址", trigger: "blur" }],
      }, // 校验规则
      format: "yyyy 年 MM 月 dd 日",
      valueFormat: "yyyy-MM-dd",
      formatTime: "HH:mm",
      valueFormatTime: "HH:mm",
      loadingKey: false,
      loadingText: "",
      init: {
        language_url: "../../../admin/tinymce/langs/zh_CN.js",
        language: "zh_CN",
        skin_url: "../../../admin/tinymce/skins/ui/oxide", // 打包部署后404，要用绝对路径引入
        // skin_url: "/tinymce/skins/ui/oxide",
        content_css: "../../../admin/tinymce/skins/content/default/content.css",
        height: 500,
        min_height: 500,
        max_width: 750,
        plugins: [
          "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link template codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave autoresize",
        ],
        toolbar:
          "code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
         styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
         table image charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs importword kityformula-editor",
        fontsize_formats: "12px 14px 16px 18px 24px 36px 48px 56px 72px",
        branding: false,
        menubar: false,
        statusbar: false,
        image_title: false,
        automatic_uploads: true,
        toolbar_drawer: false,
        images_upload_handler: this.imgEditorUpload,
      },
    };
  },
  created: function () {
    let query = this.$route.query;
    if (query.id != undefined && query.id != "") {
      this.matchId = query.id;
    }

    if (query.key != undefined && query.key != "") {
      this.editKey = query.key;
    }

    if (this.editKey == 2) {
      this.pageTitle = "编辑赛事名称";
    } else if (this.editKey == 3) {
      this.pageTitle = "查看赛事名称";
    } else {
      this.pageTitle = "新增赛事名称";
      this.matchId = "";
    }
    if (this.editKey != 1 && this.matchId != false) {
      this.getDataFn();
    }
  },
  mounted: function () {
    tinymce.init({});
  },
  methods: {
    // 查询赛事名称信息
    getDataFn: function () {
      let that = this;
      let url = "/admin/event/show";
      let data = {
        id: this.matchId,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.submitData = response.record;
            if (
              response.record.image_path != "" &&
              response.record.image_path != null &&
              response.record.image_path != undefined
            ) {
              that.imageShowUrl = that.baseAPIUrl + response.record.image_path;
            } else {
              that.imageShowUrl = "";
            }
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 提交保存
    saveBtn: function () {
      let that = this;
      let url = "";
      let data = {
        title: this.submitData.title,
        image_path: this.submitData.image_path,
        event_date: this.submitData.event_date,
        place: this.submitData.place,
        detail: this.submitData.detail,
        url: this.submitData.url,
      };
      if (this.editKey == 1) {
        url = "/admin/event/store";
      } else {
        url = "/admin/event/update";
        data.id = this.matchId;
      }
      this.$refs.submitFrom.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, JSON.stringify(data))
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("保存成功");
                that.backBtn();
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        }
      });
    },
    // 返回上一页
    backBtn: function () {
      this.$router.push({
        name: "MatchList",
      });
    },
    // 上传成功钩子
    handleAvatarSuccess: function (res, file) {
      this.imageShowUrl = URL.createObjectURL(file.raw);
      this.submitData.image_path = res.image;
      this.$message.success("上传成功");
    },
    // 上传前钩子
    beforeAvatarUpload: function (file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 3MB!");
        return false;
      }
      return true;
    },
    // 富文本上传图片
    imgEditorUpload: function (blobInfo, succFun, failFun) {
      let that = this;
      let xhr, formData;
      let file = blobInfo.blob();
      xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open("POST", that.actionUrl);
      xhr.onload = function () {
        let json;
        if (xhr.status != 200) {
          failFun("HTTP Error: " + xhr.status);
          return;
        }
        json = JSON.parse(xhr.responseText);
        if (!json || typeof json.image != "string") {
          failFun("Invalid JSON: " + xhr.responseText);
          return;
        }
        succFun(that.baseAPIUrl + json.image);
      };
      formData = new FormData();
      formData.append("file", file); //此处与源文档不一样
      formData.append("source", 6);
      xhr.send(formData);
    },
  },
};
</script>
